<template>
  <div class="addressBook">
    <div class="addressCont scrollbar" v-if="addressList && addressList.length > 0">
      <div class="addressList flexb"
        @click="handleCheck(item)"
        v-for="(item, index) in addressList" :key="index">
        <div class="account">
          <div>{{ item.name || '' }} ({{ addressChain.toUpperCase() }}{{$t('bosChain.chain')}})</div>
          <div>{{ item.address }}</div>
        </div>
        <!-- 删除 -->
        <div class="delete" @click.stop="handleDelete(item)">
          {{ $t('address.ls13') }}
        </div>
      </div>
    </div>
    <!-- 暂无添加地址 -->
    <div v-else class="addressCont flexc">
      <span>{{ $t('address.ls18') }}</span>
    </div>
    <div class="addNewAddress flexc">
      <!-- 添加新地址 -->
      <span class="colorThis" @click="handleAddAddress">+{{ $t('address.ls2') }}</span>
    </div>
    <!-- 添加新地址 -->
    <el-dialog
      class="addressDialog"
      :title="$t('address.ls4', {chain:addressChain.toUpperCase()})"
      center
      :visible.sync="addAddressVisible"
      :close-on-click-modal="false"
      width="400px"
      append-to-body>
      <div class="addAddress">
        <i class="iconfont el-icon-arrow-left" @click="addAddressVisible = false;"></i>
        <el-form label-position="top" ref="form" :rules="rules" label-width="80px" :model="form">
          <!-- 名称 -->
          <el-form-item :label="$t('address.ls5')" prop="name">
            <el-input v-model="form.name" :placeholder="$t('address.ls6')" clearable></el-input>
          </el-form-item>
          <!-- 地址 -->
          <el-form-item :label="$t('address.ls7')" prop="address">
            <el-input v-model="form.address" :placeholder="$t('address.ls8', {chain:addressChain.toUpperCase()})" clearable></el-input>
          </el-form-item>
          <!-- 确认 -->
          <el-button type="primary" style="width: 100%;" class="mb" @click="handleAddNewAddress" v-loading="comfirmLoading">
            {{ $t('address.ls12') }}
          </el-button>
        </el-form>
      </div>
    </el-dialog>
    <!-- 删除地址 -->
    <el-dialog
      class="addressDialog"
      :title="$t('address.ls10')"
      center
      :visible.sync="deleAddressVisible"
      width="400px"
      append-to-body>
      <div class="addAddress">
        <i class="iconfont el-icon-arrow-left" @click="deleAddressVisible = false;"></i>
        <div class="center word">{{ $t('address.ls3', {address: deleteItem.address, chain: addressChain.toUpperCase()}) }}</div>
        <div class="flexb">
          <el-button class="mb btn" @click="deleAddressVisible = false;">
            {{ $t('address.ls11') }}
          </el-button>
          <el-button type="primary" class="mb btn" @click="handleDeleteAddress">
            {{ $t('address.ls12') }}
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import { authorized, validateBTC, validateETH, validateTRON } from '@/utils/validate';

export default {
  name: 'addressBook', // 地址薄
  data() {
    return {
      addAddressVisible: false, // 添加新地址
      deleAddressVisible: false, // 删除地址
      form: {
        name: '', // 名称
        address: '', // 地址
      },
      addressList: [], // 地址簿列表
      deleteItem: {}, // 删除列表
      rules: null,
      comfirmLoading: false, // 添加确定loading
    }
  },
  components: {},
  props: {
    addressBookVisible: Boolean,
    type: Number,
    addressChain: String,
  },
  watch: {
    addressBookVisible: function change(val) {
      if (val) {
        this.handleAccountList();
      }
    },
    addAddressVisible: function change(val) {
      if (val && this.$refs.form) {
        this.$refs.form.resetFields();
      }
    },
    '$store.state.app.language': function change() {
      // 获取表单验证
      this.rules = this.handleRuleForm();
    },
  },
  computed: {
  },
  created() {
    this.rules = this.handleRuleForm();
  },
  mounted() {
    this.handleAccountList();
  },
  beforeDestroy() {},
  methods: {
    // 授权
    handleAuthorized(callback) {
      authorized(this, (code, result) => {
        if (code === 'error') { // 授权错误
          console.log(result); // eslint-disable-line
          callback(false)
          return;
        }
        callback('success');
      });
    },
    // 获取地址列表
    handleAccountList() {
      // TOKEN
      const token = localStorage.getItem('Frontend-Token');
      if (!token) {
        // 获取授权
        this.handleAuthorized((data) => {
          if (!data) {
            this.$emit('listenAddressBook', 'close', false);
            return;
          }
          this.handleAccountList();
        });
        return;
      }
      const param = {
        type: this.type,
        addressChain: this.addressChain
      };
      this.$http.post('/accountAddress/list', param).then((res) => {
        if (res.code !== 0) {
          this.$message.error(res.msg);
          return;
        }
        this.addressList = res.list;
      });
    },
    // 添加新地址
    handleAddNewAddress() {
      if (this.comfirmLoading) return;
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.comfirmLoading = true;
          const param = {
            type: this.type,
            name: this.form.name,
            address: this.form.address,
            addressChain: this.addressChain,
          };
          this.$http.post('/accountAddress/addAddress', param).then((res) => {
            this.comfirmLoading = false;
            // 账户存在判断
            if (res.code === 600) {
              this.$message.error(this.$t('address.ls16'));
              return;
            }
            if (res.code !== 0) {
              this.$message.error(res.msg);
              return;
            }
            this.$message.success(this.$t('address.ls14'));
            this.addAddressVisible = false;
            this.handleAccountList();
          });
        }
      })
    },
    // 删除地址
    handleDeleteAddress() {
      const param = {
        id: this.deleteItem.id
      };
      this.$http.post('/accountAddress/delete', param).then((res) => {
        if (res.code !== 0) {
          this.$message.error(res.msg);
          return;
        }
        this.$message.success(this.$t('address.ls15'));
        this.deleAddressVisible = false;
        this.handleAccountList();
      });
    },
    // 选择地址
    handleCheck(item) {
      if (this.type === 1) {
        this.$emit('listenAddressBook', 'check1', item);
      }
      if (this.type === 2) {
        this.$emit('listenAddressBook', 'check2', item);
      }
    },
    // 添加地址
    handleAddAddress() {
      this.form = {
        name: '', // 名称
        address: '', // 地址
      };
      this.addAddressVisible = true;
    },
    // 删除地址
    handleDelete(item) {
      this.deleAddressVisible = true;
      this.deleteItem = item;
    },
    // 表单验证
    handleRuleForm() {
      // 币种地址规则
      const validAddress = async (rule, value, callback) => {
        if ((!validateBTC(value) && this.addressChain === 'btc') ||
            (!validateETH(value) && this.addressChain === 'eth') ||
            (!validateTRON(value) && this.addressChain === 'tron')) {
          callback(new Error(this.$t('ct.ct84')));
          this.comfirmLoading = false;
        } else if (this.addressChain !== 'btc' && this.addressChain !== 'eth' && this.addressChain !== 'tron') {
          const status = !await this.handleValidateReceive()
          if (status) {
            callback(new Error(this.$t('ct.ct84')));
            this.comfirmLoading = false;
          }
        } else {
          callback();
        }
      };
      return {
        name: [
          { required: true, message: this.$t('address.ls6'), trigger: 'blur' },
        ],
        address: [
          { required: true, message: this.$t('address.ls17'), trigger: 'blur' },
          { validator: validAddress, trigger: 'blur' },
        ],
      }
    },
    // 验证账户是否存在
    handleValidateReceive() {
      return new Promise((resolve, reject) => {
        let nodeobj = null;
        const nodeChecked = this.$store.state.app.nodeChecked;
        nodeobj = nodeChecked[this.addressChain] || '';
        const kip = nodeobj.url || '';
        const accountParams = {
          account_name: this.form.address
        };
        axios.post(`${kip}/v1/chain/get_account`, JSON.stringify(accountParams)).then((result) => {
          if (result.status !== 200) {
            resolve(false);
          }
          resolve(true);
        }).catch(() => {
          resolve(false);
          reject();
        })
      })
    },
  },
}
</script>
<style lang="scss" scoped>
.addressBook {
  height: 500px;

  .addressCont {
    height: 460px;
    overflow: auto;
    .addressList {
      cursor: pointer;
      padding: 15px 0;
      border-bottom: 1px solid #C7C7C7;

      &:last-child {
        border-bottom: 0;
      }

      .account {
        width: 85%;
        div:nth-child(1) {
          font-size: 12px;
          color: #999;
          margin-bottom: 5px;
        }
      }
      .delete {
        width: 15%;
        cursor: pointer;
        padding-right: 5px;
        color: #999;
        text-align: center;
      }
    }
  }

  .addNewAddress {
    margin-top: 20px;
    cursor: pointer;
  }
}
.addressDialog {
  /deep/ .el-dialog__header {
    padding-top: 30px;
  }

  /deep/ .el-dialog__body {
    padding-top: 10px;
  }
}
.addAddress {
  position: relative;
  padding: 0 10px;

  .el-icon-arrow-left {
    position: absolute;
    left: 0;
    top: -45px;
    font-size: 26px;
    cursor: pointer;
  }

  .word {
    padding: 20px 0 30px;
  }

  .btn {
    width: 170px;
  }
}
</style>

